package com.foo.ui_demo_widge;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends AppCompatActivity {
    private int progress=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar);
        ProgressBar pb_3 = findViewById(R.id.pb_3);
        Button btnadd = findViewById(R.id.btn_add);
        pb_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int current=pb_3.getProgress();
                int max=pb_3.getMax();
                if (current<max){
                    pb_3.setProgress(current+10);
                }else {
                    btnadd.setEnabled(false);
                }
            }
        });
        ProgressBar pb4 = findViewById(R.id.pb_4);
       Handler handler = new Handler(Looper.myLooper(),new Handler.Callback() {
           @Override
           public boolean handleMessage(@NonNull Message msg) {
               if (msg.what == 1) {
                   pb4.setProgress(progress);
               } else {
                   Toast.makeText(ProgressBarActivity.this,
                           "加载完成", Toast.LENGTH_SHORT).show();
                   pb4.setVisibility(View.GONE);
               }


               return true;
           }
       });
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    progress+=Math.random()*10;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    if (progress<=100){
                        message.what=1;
                        handler.sendMessage(message);
                    }else {
                        message.what=-1;
                        handler.sendMessage(message);
                        break;
                    }
                }
            }
        }).start();

    }
}